home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Tools / MPW / gzip 1.2.2 / deflate.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-06-25  |  28.8 KB  |  786 lines  |  [TEXT/MPS ]

  1. /* deflate.c -- compress data using the deflation algorithm
  2.  * Copyright (C) 1992-1993 Jean-loup Gailly
  3.  * This is free software; you can redistribute it and/or modify it under the
  4.  * terms of the GNU General Public License, see the file COPYING.
  5.  */
  6.  
  7. /*
  8.  *  PURPOSE
  9.  *
  10.  *      Identify new text as repetitions of old text within a fixed-
  11.  *      length sliding window trailing behind the new text.
  12.  *
  13.  *  DISCUSSION
  14.  *
  15.  *      The "deflation" process depends on being able to identify portions
  16.  *      of the input text which are identical to earlier input (within a
  17.  *      sliding window trailing behind the input currently being processed).
  18.  *
  19.  *      The most straightforward technique turns out to be the fastest for
  20.  *      most input files: try all possible matches and select the longest.
  21.  *      The key feature of this algorithm is that insertions into the string
  22.  *      dictionary are very simple and thus fast, and deletions are avoided
  23.  *      completely. Insertions are performed at each input character, whereas
  24.  *      string matches are performed only when the previous match ends. So it
  25.  *      is preferable to spend more time in matches to allow very fast string
  26.  *      insertions and avoid deletions. The matching algorithm for small
  27.  *      strings is inspired from that of Rabin & Karp. A brute force approach
  28.  *      is used to find longer strings when a small match has been found.
  29.  *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  30.  *      (by Leonid Broukhis).
  31.  *         A previous version of this file used a more sophisticated algorithm
  32.  *      (by Fiala and Greene) which is guaranteed to run in linear amortized
  33.  *      time, but has a larger average cost, uses more memory and is patented.
  34.  *      However the F&G algorithm may be faster for some highly redundant
  35.  *      files if the parameter max_chain_length (described below) is too large.
  36.  *
  37.  *  ACKNOWLEDGEMENTS
  38.  *
  39.  *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  40.  *      I found it in 'freeze' written by Leonid Broukhis.
  41.  *      Thanks to many info-zippers for bug reports and testing.
  42.  *
  43.  *  REFERENCES
  44.  *
  45.  *      APPNOTE.TXT documentation file in PKZIP 1.93a distribution.
  46.  *
  47.  *      A description of the Rabin and Karp algorithm is given in the book
  48.  *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  49.  *
  50.  *      Fiala,E.R., and Greene,D.H.
  51.  *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  52.  *
  53.  *  INTERFACE
  54.  *
  55.  *      void lm_init (int pack_level, ush *flags)
  56.  *          Initialize the "longest match" routines for a new file
  57.  *
  58.  *      ulg deflate (void)
  59.  *          Processes a new input file and return its compressed length. Sets
  60.  *          the compressed length, crc, deflate flags and internal file
  61.  *          attributes.
  62.  */
  63.  
  64. #ifdef macintosh
  65. #include <cursorctl.h>
  66. #endif
  67.  
  68. #include <stdio.h>
  69.  
  70. #include "tailor.h"
  71. #include "gzip.h"
  72. #include "lzw.h" /* just for consistency checking */
  73.  
  74. #ifndef lint
  75. static char rcsid[] = "$Id: deflate.c,v 0.14 1993/06/12 20:11:10 jloup Exp $";
  76. #endif
  77.  
  78. /* ===========================================================================
  79.  * Configuration parameters
  80.  */
  81.  
  82. /* Compile with MEDIUM_MEM to reduce the memory requirements or
  83.  * with SMALL_MEM to use as little memory as possible. Use BIG_MEM if the
  84.  * entire input file can be held in memory (not possible on 16 bit systems).
  85.  * Warning: defining these symbols affects HASH_BITS (see below) and thus
  86.  * affects the compression ratio. The compressed output
  87.  * is still correct, and might even be smaller in some cases.
  88.  */
  89.  
  90. #ifdef SMALL_MEM
  91. #   define HASH_BITS  13  /* Number of bits used to hash strings */
  92. #endif
  93. #ifdef MEDIUM_MEM
  94. #   define HASH_BITS  14
  95. #endif
  96. #ifndef HASH_BITS
  97. #   define HASH_BITS  15
  98.    /* For portability to 16 bit machines, do not use values above 15. */
  99. #endif
  100.  
  101. /* To save space (see unlzw.c), we overlay prev+head with tab_prefix and
  102.  * window with tab_suffix. Check that we can do this:
  103.  */
  104. #if WSIZE<<1 > 1<<BITS
  105.    error: cannot overlay window with tab_suffix and prev with tab_prefix0
  106. #endif
  107. #if HASH_BITS > BITS-1
  108.    error: cannot overlay head with tab_prefix1
  109. #endif
  110.  
  111. #define HASH_SIZE (unsigned)(1<<HASH_BITS)
  112. #define HASH_MASK (HASH_SIZE-1)
  113. #define WMASK     (WSIZE-1)
  114. /* HASH_SIZE and WSIZE must be powers of two */
  115.  
  116. #define NIL 0
  117. /* Tail of hash chains */
  118.  
  119. #define FAST 4
  120. #define SLOW 2
  121. /* speed options for the general purpose bit flag */
  122.  
  123. #ifndef TOO_FAR
  124. #  define TOO_FAR 4096
  125. #endif
  126. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  127.  
  128. /* ===========================================================================
  129.  * Local data used by the "longest match" routines.
  130.  */
  131.  
  132. typedef ush Pos;
  133. typedef unsigned IPos;
  134. /* A Pos is an index in the character window. We use short instead of int to
  135.  * save space in the various tables. IPos is used only for parameter passing.
  136.  */
  137.  
  138. /* DECLARE(uch, window, 2L*WSIZE); */
  139. /* Sliding window. Input bytes are read into the second half of the window,
  140.  * and move to the first half later to keep a dictionary of at least WSIZE
  141.  * bytes. With this organization, matches are limited to a distance of
  142.  * WSIZE-MAX_MATCH bytes, but this ensures that IO is always
  143.  * performed with a length multiple of the block size. Also, it limits
  144.  * the window size to 64K, which is quite useful on MSDOS.
  145.  * To do: limit the window size to WSIZE+BSZ if SMALL_MEM (the code would
  146.  * be less efficient).
  147.  */
  148.  
  149. /* DECLARE(Pos, prev, WSIZE); */
  150. /* Link to older string with same hash index. To limit the size of this
  151.  * array to 64K, this link is maintained only for the last 32K strings.
  152.  * An index in this array is thus a window index modulo 32K.
  153.  */
  154.  
  155. /* DECLARE(Pos, head, 1<<HASH_BITS); */
  156. /* Heads of the hash chains or NIL. */
  157.  
  158. ulg window_size = (ulg)2*WSIZE;
  159. /* window size, 2*WSIZE except for MMAP or BIG_MEM, where it is the
  160.  * input file length plus MIN_LOOKAHEAD.
  161.  */
  162.  
  163. long block_start;
  164. /* window position at the beginning of the current output block. Gets
  165.  * negative when the window is moved backwards.
  166.  */
  167.  
  168. local unsigned ins_h;  /* hash index of string to be inserted */
  169.  
  170. #define H_SHIFT  ((HASH_BITS+MIN_MATCH-1)/MIN_MATCH)
  171. /* Number of bits by which ins_h and del_h must be shifted at each
  172.  * input step. It must be such that after MIN_MATCH steps, the oldest
  173.  * byte no longer takes part in the hash key, that is:
  174.  *   H_SHIFT * MIN_MATCH >= HASH_BITS
  175.  */
  176.  
  177. unsigned int near prev_length;
  178. /* Length of the best match at previous step. Matches not greater than this
  179.  * are discarded. This is used in the lazy match evaluation.
  180.  */
  181.  
  182.       unsigned near strstart;      /* start of string to insert */
  183.       unsigned near match_start;   /* start of matching string */
  184. local int           eofile;        /* flag set at end of input file */
  185. local unsigned      lookahead;     /* number of valid bytes ahead in window */
  186.  
  187. unsigned near max_chain_length;
  188. /* To speed up deflation, hash chains are never searched beyond this length.
  189.  * A higher limit improves compression ratio but degrades the speed.
  190.  */
  191.  
  192. local unsigned int max_lazy_match;
  193. /* Attempt to find a better match only when the current match is strictly
  194.  * smaller than this value. This mechanism is used only for compression
  195.  * levels >= 4.
  196.  */
  197. #define max_insert_length  max_lazy_match
  198. /* Insert new strings in the hash table only if the match length
  199.  * is not greater than this length. This saves time but degrades compression.
  200.  * max_insert_length is used only for compression levels <= 3.
  201.  */
  202.  
  203. local int compr_level;
  204. /* compression level (1..9) */
  205.  
  206. int near good_match;
  207. /* Use a faster search when the previous match is longer than this */
  208.  
  209.  
  210. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  211.  * the desired pack level (0..9). The values given below have been tuned to
  212.  * exclude worst case performance for pathological files. Better values may be
  213.  * found for specific files.
  214.  */
  215.  
  216. typedef struct config {
  217.    ush good_length; /* reduce lazy search above this match length */
  218.    ush max_lazy;    /* do not perform lazy search above this match length */
  219.    ush nice_length; /* quit search above this match length */
  220.    ush max_chain;
  221. } config;
  222.  
  223. #ifdef  FULL_SEARCH
  224. # define nice_match MAX_MATCH
  225. #else
  226.   int near nice_match; /* Stop searching when current match exceeds this */
  227. #endif
  228.  
  229. local config configuration_table[10] = {
  230. /*      good lazy nice chain */
  231. /* 0 */ {0,    0,  0,    0},  /* store only */
  232. /* 1 */ {4,    4,  8,    4},  /* maximum speed, no lazy matches */
  233. /* 2 */ {4,    5, 16,    8},
  234. /* 3 */ {4,    6, 32,   32},
  235.  
  236. /* 4 */ {4,    4, 16,   16},  /* lazy matches */
  237. /* 5 */ {8,   16, 32,   32},
  238. /* 6 */ {8,   16, 128, 128},
  239. /* 7 */ {8,   32, 128, 256},
  240. /* 8 */ {32, 128, 258, 1024},
  241. /* 9 */ {32, 258, 258, 4096}}; /* maximum compression */
  242.  
  243. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  244.  * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  245.  * meaning.
  246.  */
  247.  
  248. #define EQUAL 0
  249. /* result of memcmp for equal strings */
  250.  
  251. /* ===========================================================================
  252.  *  Prototypes for local functions.
  253.  */
  254. local void fill_window   OF((void));
  255. local ulg deflate_fast   OF((void));
  256.  
  257.       int  longest_match OF((IPos cur_match));
  258. #ifdef ASMV
  259.       void match_init OF((void)); /* asm code initialization */
  260. #endif
  261.  
  262. #ifdef DEBUG
  263. local  void check_match OF((IPos start, IPos match, int length));
  264. #endif
  265.  
  266. /* ===========================================================================
  267.  * Update a hash value with the given input byte
  268.  * IN  assertion: all calls to to UPDATE_HASH are made with consecutive
  269.  *    input characters, so that a running hash key can be computed from the
  270.  *    previous key instead of complete recalculation each time.
  271.  */
  272. #define UPDATE_HASH(h,c) (h = (((h)<<H_SHIFT) ^ (c)) & HASH_MASK)
  273.  
  274. /* ===========================================================================
  275.  * Insert string s in the dictionary and set match_head to the previous head
  276.  * of the hash chain (the most recent string with same hash key). Return
  277.  * the previous length of the hash chain.
  278.  * IN  assertion: all calls to to INSERT_STRING are made with consecutive
  279.  *    input characters and the first MIN_MATCH bytes of s are valid
  280.  *    (except for the last MIN_MATCH-1 bytes of the input file).
  281.  */
  282. #define INSERT_STRING(s, match_head) \
  283.    (UPDATE_HASH(ins_h, window[(s) + MIN_MATCH-1]), \
  284.     prev[(s) & WMASK] = match_head = head[ins_h], \
  285.     head[ins_h] = (s))
  286.  
  287. /* ===========================================================================
  288.  * Initialize the "longest match" routines for a new file
  289.  */
  290. void lm_init (pack_level, flags)
  291.     int pack_level; /* 0: store, 1: best speed, 9: best compression */
  292.     ush *flags;     /* general purpose bit flag */
  293. {
  294.     register unsigned j;
  295.  
  296.     if (pack_level < 1 || pack_level > 9) error("bad pack level");
  297.     compr_level = pack_level;
  298.  
  299.     /* Initialize the hash table. */
  300. #if defined(MAXSEG_64K) && HASH_BITS == 15
  301.     for (j = 0;  j < HASH_SIZE; j++) head[j] = NIL;
  302. #else
  303.     memzero((char*)head, HASH_SIZE*sizeof(*head));
  304. #endif
  305.     /* prev will be initialized on the fly */
  306.  
  307.     /* Set the default configuration parameters:
  308.      */
  309.     max_lazy_match   = configuration_table[pack_level].max_lazy;
  310.     good_match       = configuration_table[pack_level].good_length;
  311. #ifndef FULL_SEARCH
  312.     nice_match       = configuration_table[pack_level].nice_length;
  313. #endif
  314.     max_chain_length = configuration_table[pack_level].max_chain;
  315.     if (pack_level == 1) {
  316.        *flags |= FAST;
  317.     } else if (pack_level == 9) {
  318.        *flags |= SLOW;
  319.     }
  320.     /* ??? reduce max_chain_length for binary files */
  321.  
  322.     strstart = 0;
  323.     block_start = 0L;
  324. #ifdef ASMV
  325.     match_init(); /* initialize the asm code */
  326. #endif
  327.  
  328.     lookahead = read_buf((char*)window,
  329.              sizeof(int) <= 2 ? (unsigned)WSIZE : 2*WSIZE);
  330.  
  331.     if (lookahead == 0 || lookahead == (unsigned)EOF) {
  332.        eofile = 1, lookahead = 0;
  333.        return;
  334.     }
  335.     eofile = 0;
  336.     /* Make sure that we always have enough lookahead. This is important
  337.      * if input comes from a device such as a tty.
  338.      */
  339.     while (lookahead < MIN_LOOKAHEAD && !eofile) fill_window();
  340.  
  341.     ins_h = 0;
  342.     for (j=0; j<MIN_MATCH-1; j++) UPDATE_HASH(ins_h, window[j]);
  343.     /* If lookahead < MIN_MATCH, ins_h is garbage, but this is
  344.      * not important since only literal bytes will be emitted.
  345.      */
  346. }
  347.  
  348. /* ===========================================================================
  349.  * Set match_start to the longest match starting at the given string and
  350.  * return its length. Matches shorter or equal to prev_length are discarded,
  351.  * in which case the result is equal to prev_length and match_start is
  352.  * garbage.
  353.  * IN assertions: cur_match is the head of the hash chain for the current
  354.  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  355.  */
  356. #ifndef ASMV
  357. /* For MSDOS, OS/2 and 386 Unix, an optimized version is in match.asm or
  358.  * match.s. The code is functionally equivalent, so you can use the C version
  359.  * if desired.
  360.  */
  361. int longest_match(cur_match)
  362.     IPos cur_match;                             /* current match */
  363. {
  364.     unsigned chain_length = max_chain_length;   /* max hash chain length */
  365.     register uch *scan = window + strstart;     /* current string */
  366.     register uch *match;                        /* matched string */
  367.     register int len;                           /* length of current match */
  368.     int best_len = prev_length;                 /* best match length so far */
  369.     IPos limit = strstart > (IPos)MAX_DIST ? strstart - (IPos)MAX_DIST : NIL;
  370.     /* Stop when cur_match becomes <= limit. To simplify the code,
  371.      * we prevent matches with the string of window index 0.
  372.      */
  373.  
  374. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  375.  * It is easy to get rid of this optimization if necessary.
  376.  */
  377. #if HASH_BITS < 8 || MAX_MATCH != 258
  378.    error: Code too clever
  379. #endif
  380.  
  381. #ifdef UNALIGNED_OK
  382.     /* Compare two bytes at a time. Note: this is not always beneficial.
  383.      * Try with and without -DUNALIGNED_OK to check.
  384.      */
  385.     register uch *strend = window + strstart + MAX_MATCH - 1;
  386.     register ush scan_start = *(ush*)scan;
  387.     register ush scan_end   = *(ush*)(scan+best_len-1);
  388. #else
  389.     register uch *strend = window + strstart + MAX_MATCH;
  390.     register uch scan_end1  = scan[best_len-1];
  391.     register uch scan_end   = scan[best_len];
  392. #endif
  393.  
  394.     /* Do not waste too much time if we already have a good match: */
  395.     if (prev_length >= good_match) {
  396.         chain_length >>= 2;
  397.     }
  398.     Assert(strstart <= window_size-MIN_LOOKAHEAD, "insufficient lookahead");
  399.  
  400.     do {
  401.         Assert(cur_match < strstart, "no future");
  402.         match = window + cur_match;
  403.  
  404.         /* Skip to next match if the match length cannot increase
  405.          * or if the match length is less than 2:
  406.          */
  407. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  408.         /* This code assumes sizeof(unsigned short) == 2. Do not use
  409.          * UNALIGNED_OK if your compiler uses a different size.
  410.          */
  411.         if (*(ush*)(match+best_len-1) != scan_end ||
  412.             *(ush*)match != scan_start) continue;
  413.  
  414.         /* It is not necessary to compare scan[2] and match[2] since they are
  415.          * always equal when the other bytes match, given that the hash keys
  416.          * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  417.          * strstart+3, +5, ... up to strstart+257. We check for insufficient
  418.          * lookahead only every 4th comparison; the 128th check will be made
  419.          * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  420.          * necessary to put more guard bytes at the end of the window, or
  421.          * to check more often for insufficient lookahead.
  422.          */
  423.         scan++, match++;
  424.         do {
  425.         } while (*(ush*)(scan+=2) == *(ush*)(match+=2) &&
  426.                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
  427.                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
  428.                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
  429.                  scan < strend);
  430.         /* The funny "do {}" generates better code on most compilers */
  431.  
  432.         /* Here, scan <= window+strstart+257 */
  433.         Assert(scan <= window+(unsigned)(window_size-1), "wild scan");
  434.         if (*scan == *match) scan++;
  435.  
  436.         len = (MAX_MATCH - 1) - (int)(strend-scan);
  437.         scan = strend - (MAX_MATCH-1);
  438.  
  439. #else /* UNALIGNED_OK */
  440.  
  441.         if (match[best_len]   != scan_end  ||
  442.             match[best_len-1] != scan_end1 ||
  443.             *match            != *scan     ||
  444.             *++match          != scan[1])      continue;
  445.  
  446.         /* The check at best_len-1 can be removed because it will be made
  447.          * again later. (This heuristic is not always a win.)
  448.          * It is not necessary to compare scan[2] and match[2] since they
  449.          * are always equal when the other bytes match, given that
  450.          * the hash keys are equal and that HASH_BITS >= 8.
  451.          */
  452.         scan += 2, match++;
  453.  
  454.         /* We check for insufficient lookahead only every 8th comparison;
  455.          * the 256th check will be made at strstart+258.
  456.          */
  457.         do {
  458.         } while (*++scan == *++match && *++scan == *++match &&
  459.                  *++scan == *++match && *++scan == *++match &&
  460.                  *++scan == *++match && *++scan == *++match &&
  461.                  *++scan == *++match && *++scan == *++match &&
  462.                  scan < strend);
  463.  
  464.         len = MAX_MATCH - (int)(strend - scan);
  465.         scan = strend - MAX_MATCH;
  466.  
  467. #endif /* UNALIGNED_OK */
  468.  
  469.         if (len > best_len) {
  470.             match_start = cur_match;
  471.             best_len = len;
  472.             if (len >= nice_match) break;
  473. #ifdef UNALIGNED_OK
  474.             scan_end = *(ush*)(scan+best_len-1);
  475. #else
  476.             scan_end1  = scan[best_len-1];
  477.             scan_end   = scan[best_len];
  478. #endif
  479.         }
  480.     } while ((cur_match = prev[cur_match & WMASK]) > limit
  481.          && --chain_length != 0);
  482.  
  483.     return best_len;
  484. }
  485. #endif /* ASMV */
  486.  
  487. #ifdef DEBUG
  488. /* ===========================================================================
  489.  * Check that the match at match_start is indeed a match.
  490.  */
  491. local void check_match(start, match, length)
  492.     IPos start, match;
  493.     int length;
  494. {
  495.     /* check that the match is indeed a match */
  496.     if (memcmp((char*)window + match,
  497.                 (char*)window + start, length) != EQUAL) {
  498.         fprintf(stderr,
  499.             " start %d, match %d, length %d\n",
  500.             start, match, length);
  501.         error("invalid match");
  502.     }
  503.     if (verbose > 1) {
  504.         fprintf(stderr,"\\[%d,%d]", start-match, length);
  505.         do { putc(window[start++], stderr); } while (--length != 0);
  506.     }
  507. }
  508. #else
  509. #  define check_match(start, match, length)
  510. #endif
  511.  
  512. /* ===========================================================================
  513.  * Fill the window when the lookahead becomes insufficient.
  514.  * Updates strstart and lookahead, and sets eofile if end of input file.
  515.  * IN assertion: lookahead < MIN_LOOKAHEAD && strstart + lookahead > 0
  516.  * OUT assertions: at least one byte has been read, or eofile is set;
  517.  *    file reads are performed for at least two bytes (required for the
  518.  *    translate_eol option).
  519.  */
  520. local void fill_window()
  521. {
  522.     register unsigned n, m;
  523.     unsigned more = (unsigned)(window_size - (ulg)lookahead - (ulg)strstart);
  524.     /* Amount of free space at the end of the window. */
  525.  
  526.     /* If the window is almost full and there is insufficient lookahead,
  527.      * move the upper half to the lower one to make room in the upper half.
  528.      */
  529.     if (more == (unsigned)EOF) {
  530.         /* Very unlikely, but possible on 16 bit machine if strstart == 0
  531.          * and lookahead == 1 (input done one byte at time)
  532.          */
  533.         more--;
  534.     } else if (strstart >= WSIZE+MAX_DIST) {
  535.         /* By the IN assertion, the window is not empty so we can't confuse
  536.          * more == 0 with more == 64K on a 16 bit machine.
  537.          */
  538.         Assert(window_size == (ulg)2*WSIZE, "no sliding with BIG_MEM");
  539.  
  540.         memcpy((char*)window, (char*)window+WSIZE, (unsigned)WSIZE);
  541.         match_start -= WSIZE;
  542.         strstart    -= WSIZE; /* we now have strstart >= MAX_DIST: */
  543.  
  544.         block_start -= (long) WSIZE;
  545.  
  546.         for (n = 0; n < HASH_SIZE; n++) {
  547.             m = head[n];
  548.             head[n] = (Pos)(m >= WSIZE ? m-WSIZE : NIL);
  549.         }
  550.         for (n = 0; n < WSIZE; n++) {
  551.             m = prev[n];
  552.             prev[n] = (Pos)(m >= WSIZE ? m-WSIZE : NIL);
  553.             /* If n is not on any hash chain, prev[n] is garbage but
  554.              * its value will never be used.
  555.              */
  556.         }
  557.         more += WSIZE;
  558.     }
  559.     /* At this point, more >= 2 */
  560.     if (!eofile) {
  561.         n = read_buf((char*)window+strstart+lookahead, more);
  562.         if (n == 0 || n == (unsigned)EOF) {
  563.             eofile = 1;
  564.         } else {
  565.             lookahead += n;
  566.         }
  567.     }
  568. }
  569.  
  570. /* ===========================================================================
  571.  * Flush the current block, with given end-of-file flag.
  572.  * IN assertion: strstart is set to the end of the current match.
  573.  */
  574. #define FLUSH_BLOCK(eof) \
  575.    flush_block(block_start >= 0L ? (char*)&window[(unsigned)block_start] : \
  576.                 (char*)NULL, (long)strstart - block_start, (eof))
  577.  
  578. /* ===========================================================================
  579.  * Processes a new input file and return its compressed length. This
  580.  * function does not perform lazy evaluationof matches and inserts
  581.  * new strings in the dictionary only for unmatched strings. It is used
  582.  * only for the fast compression options.
  583.  */
  584. local ulg deflate_fast()
  585. {
  586.     IPos hash_head; /* head of the hash chain */
  587.     int flush;      /* set if current block must be flushed */
  588.     unsigned match_length = 0;  /* length of best match */
  589. #ifdef macintosh
  590.     int xxx = 1;
  591. #endif
  592.  
  593.     prev_length = MIN_MATCH-1;
  594.     while (lookahead != 0) {
  595. #ifdef macintosh
  596.     if( xxx == 4 ) {
  597.         SpinCursor( -1 );
  598.         xxx = 1;
  599.     } else xxx++;
  600. #endif
  601.         /* Insert the string window[strstart .. strstart+2] in the
  602.          * dictionary, and set hash_head to the head of the hash chain:
  603.          */
  604.         INSERT_STRING(strstart, hash_head);
  605.  
  606.         /* Find the longest match, discarding those <= prev_length.
  607.          * At this point we have always match_length < MIN_MATCH
  608.          */
  609.         if (hash_head != NIL && strstart - hash_head <= MAX_DIST) {
  610.             /* To simplify the code, we prevent matches with the string
  611.              * of window index 0 (in particular we have to avoid a match
  612.              * of the string with itself at the start of the input file).
  613.              */
  614.             match_length = longest_match (hash_head);
  615.             /* longest_match() sets match_start */
  616.             if (match_length > lookahead) match_length = lookahead;
  617.         }
  618.         if (match_length >= MIN_MATCH) {
  619.             check_match(strstart, match_start, match_length);
  620.  
  621.             flush = ct_tally(strstart-match_start, match_length - MIN_MATCH);
  622.  
  623.             lookahead -= match_length;
  624.  
  625.         /* Insert new strings in the hash table only if the match length
  626.              * is not too large. This saves time but degrades compression.
  627.              */
  628.             if (match_length <= max_insert_length) {
  629.                 match_length--; /* string at strstart already in hash table */
  630.                 do {
  631.                     strstart++;
  632.                     INSERT_STRING(strstart, hash_head);
  633.                     /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  634.                      * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
  635.                      * these bytes are garbage, but it does not matter since
  636.                      * the next lookahead bytes will be emitted as literals.
  637.                      */
  638.                 } while (--match_length != 0);
  639.             strstart++; 
  640.             } else {
  641.             strstart += match_length;
  642.             match_length = 0;
  643.             ins_h = window[strstart];
  644.             UPDATE_HASH(ins_h, window[strstart+1]);
  645. #if MIN_MATCH != 3
  646.                 Call UPDATE_HASH() MIN_MATCH-3 more times
  647. #endif
  648.             }
  649.         } else {
  650.             /* No match, output a literal byte */
  651.             Tracevv((stderr,"%c",window[strstart]));
  652.             flush = ct_tally (0, window[strstart]);
  653.             lookahead--;
  654.         strstart++; 
  655.         }
  656.         if (flush) FLUSH_BLOCK(0), block_start = strstart;
  657.  
  658.         /* Make sure that we always have enough lookahead, except
  659.          * at the end of the input file. We need MAX_MATCH bytes
  660.          * for the next match, plus MIN_MATCH bytes to insert the
  661.          * string following the next match.
  662.          */
  663.         while (lookahead < MIN_LOOKAHEAD && !eofile) fill_window();
  664.  
  665.     }
  666.     return FLUSH_BLOCK(1); /* eof */
  667. }
  668.  
  669. /* ===========================================================================
  670.  * Same as above, but achieves better compression. We use a lazy
  671.  * evaluation for matches: a match is finally adopted only if there is
  672.  * no better match at the next window position.
  673.  */
  674. ulg deflate()
  675. {
  676.     IPos hash_head;          /* head of hash chain */
  677.     IPos prev_match;         /* previous match */
  678.     int flush;               /* set if current block must be flushed */
  679.     int match_available = 0; /* set if previous match exists */
  680.     register unsigned match_length = MIN_MATCH-1; /* length of best match */
  681. #ifdef macintosh
  682.     int xxx = 1;
  683. #endif
  684. #ifdef DEBUG
  685.     extern long isize;        /* byte length of input file, for debug only */
  686. #endif
  687.  
  688.     if (compr_level <= 3) return deflate_fast(); /* optimized for speed */
  689.  
  690.     /* Process the input block. */
  691.     while (lookahead != 0) {
  692. #ifdef macintosh
  693.     if( xxx == 4 ) {
  694.         SpinCursor( -1 );
  695.         xxx = 1;
  696.     } else xxx++;
  697. #endif
  698.         /* Insert the string window[strstart .. strstart+2] in the
  699.          * dictionary, and set hash_head to the head of the hash chain:
  700.          */
  701.         INSERT_STRING(strstart, hash_head);
  702.  
  703.         /* Find the longest match, discarding those <= prev_length.
  704.          */
  705.         prev_length = match_length, prev_match = match_start;
  706.         match_length = MIN_MATCH-1;
  707.  
  708.         if (hash_head != NIL && prev_length < max_lazy_match &&
  709.             strstart - hash_head <= MAX_DIST) {
  710.             /* To simplify the code, we prevent matches with the string
  711.              * of window index 0 (in particular we have to avoid a match
  712.              * of the string with itself at the start of the input file).
  713.              */
  714.             match_length = longest_match (hash_head);
  715.             /* longest_match() sets match_start */
  716.             if (match_length > lookahead) match_length = lookahead;
  717.  
  718.             /* Ignore a length 3 match if it is too distant: */
  719.             if (match_length == MIN_MATCH && strstart-match_start > TOO_FAR){
  720.                 /* If prev_match is also MIN_MATCH, match_start is garbage
  721.                  * but we will ignore the current match anyway.
  722.                  */
  723.                 match_length--;
  724.             }
  725.         }
  726.         /* If there was a match at the previous step and the current
  727.          * match is not better, output the previous match:
  728.          */
  729.         if (prev_length >= MIN_MATCH && match_length <= prev_length) {
  730.  
  731.             check_match(strstart-1, prev_match, prev_length);
  732.  
  733.             flush = ct_tally(strstart-1-prev_match, prev_length - MIN_MATCH);
  734.  
  735.             /* Insert in hash table all strings up to the end of the match.
  736.              * strstart-1 and strstart are already inserted.
  737.              */
  738.             lookahead -= prev_length-1;
  739.             prev_length -= 2;
  740.             do {
  741.                 strstart++;
  742.                 INSERT_STRING(strstart, hash_head);
  743.                 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  744.                  * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
  745.                  * these bytes are garbage, but it does not matter since the
  746.                  * next lookahead bytes will always be emitted as literals.
  747.                  */
  748.             } while (--prev_length != 0);
  749.             match_available = 0;
  750.             match_length = MIN_MATCH-1;
  751.             strstart++;
  752.             if (flush) FLUSH_BLOCK(0), block_start = strstart;
  753.  
  754.         } else if (match_available) {
  755.             /* If there was no match at the previous position, output a
  756.              * single literal. If there was a match but the current match
  757.              * is longer, truncate the previous match to a single literal.
  758.              */
  759.             Tracevv((stderr,"%c",window[strstart-1]));
  760.             if (ct_tally (0, window[strstart-1])) {
  761.                 FLUSH_BLOCK(0), block_start = strstart;
  762.             }
  763.             strstart++;
  764.             lookahead--;
  765.         } else {
  766.             /* There is no previous match to compare with, wait for
  767.              * the next step to decide.
  768.              */
  769.             match_available = 1;
  770.             strstart++;
  771.             lookahead--;
  772.         }
  773.         Assert (strstart <= isize && lookahead <= isize, "a bit too far");
  774.  
  775.         /* Make sure that we always have enough lookahead, except
  776.          * at the end of the input file. We need MAX_MATCH bytes
  777.          * for the next match, plus MIN_MATCH bytes to insert the
  778.          * string following the next match.
  779.          */
  780.         while (lookahead < MIN_LOOKAHEAD && !eofile) fill_window();
  781.     }
  782.     if (match_available) ct_tally (0, window[strstart-1]);
  783.  
  784.     return FLUSH_BLOCK(1); /* eof */
  785. }
  786.